import { createRouter, createWebHistory } from 'vue-router'
import { close, start } from '@/plugins/nprogress'
import { useCommonStore } from '@/store/common'
import { useRouteStore } from '@/store/modules/routes'

// 固定路由
const constantRoutes: Routes.RouterListItem[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import('@/views/prompt/404.vue'),
    meta: {
      title: '找不到页面'
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: () => import('@/layouts/index.vue'),
      redirect: '/dashboard',
      children: []
    },
    ...constantRoutes
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const commonStore = useCommonStore()
  const routeStore = useRouteStore()
  start()
  if (!commonStore.token) {
    if (to.path === '/login') {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    // 动态注入路由内容
    if (routeStore.routeData.length > 0) {
      if (from.path === '/login') {
        next()
      } else {
        if (routeStore.isGetRouter) {
          next()
        } else {
          routeStore.setRoutes(routeStore.routeData, false)
          next({ ...to, replace: true })
        }
      }
    }
  }
})

router.afterEach(() => {
  close()
})

export default router
